import time
import threading
import json
import sys
from simulator_data import (
    simulator_settings, 
    generate_robot_status, 
    generate_gait_data, 
    generate_alert_data,
    generate_and_save_data
)

class CommandLineSimulator:
    def __init__(self):
        self.running = True
        self.interval = 60  # 默认每60秒生成一次数据
        self.save_to_db = True
        self.data_thread = None
    
    def start(self):
        """启动模拟器"""
        print("===== 四足机器人数据模拟器 (命令行版) =====")
        print("输入 'help' 查看可用命令")
        
        # 启动数据生成线程
        self.start_data_generation()
        
        # 命令行循环
        while self.running:
            try:
                command = input("\n> ").strip().lower()
                self.process_command(command)
            except KeyboardInterrupt:
                print("\n正在停止模拟器...")
                self.running = False
                break
            except Exception as e:
                print(f"错误: {str(e)}")
    
    def process_command(self, command):
        """处理命令"""
        if command == "help":
            self.show_help()
        elif command == "status":
            self.show_status()
        elif command == "generate":
            self.generate_once()
        elif command == "interval":
            self.change_interval()
        elif command == "settings":
            self.show_settings()
        elif command == "toggle":
            self.toggle_save_to_db()
        elif command == "quit" or command == "exit":
            print("正在停止模拟器...")
            self.running = False
        else:
            print(f"未知命令: '{command}'，输入 'help' 查看可用命令")
    
    def show_help(self):
        """显示帮助信息"""
        print("\n可用命令:")
        print("  help      - 显示此帮助信息")
        print("  status    - 显示当前模拟器状态")
        print("  generate  - 手动生成一次数据")
        print("  interval  - 更改数据生成间隔")
        print("  settings  - 显示当前设置")
        print("  toggle    - 切换是否保存到数据库")
        print("  quit/exit - 退出模拟器")
    
    def show_status(self):
        """显示当前状态"""
        status = "运行中" if self.data_thread and self.data_thread.is_alive() else "已停止"
        print(f"\n当前状态: {status}")
        print(f"生成间隔: {self.interval} 秒")
        print(f"保存到数据库: {'是' if self.save_to_db else '否'}")
    
    def generate_once(self):
        """手动生成一次数据"""
        print("\n正在生成数据...")
        data = generate_and_save_data(save_to_db=self.save_to_db)
        print("数据生成完成")
    
    def change_interval(self):
        """更改数据生成间隔"""
        try:
            new_interval = input("输入新的间隔时间（秒）: ")
            new_interval = int(new_interval)
            if new_interval < 1:
                print("间隔时间必须大于0")
                return
            self.interval = new_interval
            print(f"间隔时间已更新为 {self.interval} 秒")
            
            # 重启数据生成线程
            self.restart_data_generation()
        except ValueError:
            print("请输入有效的数字")
    
    def show_settings(self):
        """显示当前设置"""
        print("\n当前设置:")
        print(json.dumps(simulator_settings, indent=2, ensure_ascii=False))
    
    def toggle_save_to_db(self):
        """切换是否保存到数据库"""
        self.save_to_db = not self.save_to_db
        print(f"保存到数据库: {'是' if self.save_to_db else '否'}")
        
        # 重启数据生成线程
        self.restart_data_generation()
    
    def start_data_generation(self):
        """启动数据生成线程"""
        self.stop_data_generation()  # 先停止现有线程
        
        self.data_thread = threading.Thread(
            target=self.generate_data_thread,
            daemon=True
        )
        self.data_thread.start()
        print(f"数据生成线程已启动，间隔 {self.interval} 秒")
    
    def stop_data_generation(self):
        """停止数据生成线程"""
        if self.data_thread and self.data_thread.is_alive():
            self.data_thread_running = False
            self.data_thread.join(2)  # 等待最多2秒
            print("数据生成线程已停止")
    
    def restart_data_generation(self):
        """重启数据生成线程"""
        self.start_data_generation()
    
    def generate_data_thread(self):
        """数据生成线程"""
        self.data_thread_running = True
        while self.data_thread_running and self.running:
            try:
                generate_and_save_data(save_to_db=self.save_to_db)
                print(f"\n[{time.strftime('%Y-%m-%d %H:%M:%S')}] 数据已生成" + (" 并保存到数据库" if self.save_to_db else ""))
                print("> ", end="", flush=True)  # 保持命令提示符
                
                # 休眠指定的间隔时间
                for i in range(self.interval):
                    if not self.data_thread_running or not self.running:
                        break
                    time.sleep(1)
            except Exception as e:
                print(f"生成数据时出错: {str(e)}")
                time.sleep(5)  # 出错后等待5秒再重试

if __name__ == "__main__":
    try:
        simulator = CommandLineSimulator()
        simulator.start()
    except KeyboardInterrupt:
        print("\n模拟器已停止")
    except Exception as e:
        print(f"启动模拟器时出错: {str(e)}")
    finally:
        sys.exit(0) 